package com.example.myapplication.RemoteData;

import androidx.annotation.NonNull;
import com.example.myapplication.AsyncTasks.GetJsonCallBack;
import com.example.myapplication.Note;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RemoteDataJsonHelper {
  ArrayList<Note>noteArrayList;
  public void UpLoadDataToServer(ArrayList<Note> notes) {
    OkHttpClient client = new OkHttpClient();
    //将数据类型转换为Json字符串
    Gson gson = new Gson();
    String json = gson.toJson(notes);
    //创建一个RequestBody来包含Json数据
    RequestBody body = RequestBody.create(json, MediaType.parse("application/json; charset=utf-8"));
    Request request = new Request.Builder().url("http://mcljy.wicp.net/wcj/").post(body).build();
    //发送请求并处理响应
    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(@NonNull Call call, @NonNull IOException e) {
        System.out.println("返回的结果是："+call.toString());
        System.out.println("具体信息："+e.toString());

        System.out.println("Post请求发送失败");
      }


      @Override public void onResponse(@NonNull Call call, @NonNull Response response)
          throws IOException {

        System.out.println("Post请求发送成功");
      }
    });
  }

  public void DownLoadDataFromServer(GetJsonCallBack callBack) {
    noteArrayList = new ArrayList<>();

    String url = "http://mcljy.wicp.net/wcj/getjson/";
    Request request = new Request.Builder().url(url).build();

    OkHttpClient client = new OkHttpClient();

    client.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(@NonNull Call call, @NonNull IOException e) {
        System.out.println("请求失败了");
      }

      @Override public void onResponse(@NonNull Call call, @NonNull Response response)
          throws IOException {
        if (response.isSuccessful()) {
          //获取响应数据并处理
          String responseData = response.body().string();
          ArrayList<Note> notes = parseJsonToNoteList(responseData);
          callBack.OnGetFinished(notes);
          //noteArrayList.clear();
          //noteArrayList.addAll(notes);
        }
      }
    });

  }

  private static ArrayList<Note> parseJsonToNoteList(String json) {
    Gson gson = new Gson();
    Type noteListType = new TypeToken<ArrayList<Note>>() {}.getType();
    return gson.fromJson(json, noteListType);
  }

}
